package cn.tedu.ivos1.geofence.service.impl;

import cn.tedu.ivos1.base.exception.ServiceException;
import cn.tedu.ivos1.base.response.StatusCode;
import cn.tedu.ivos1.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos1.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos1.geofence.pojo.dto.GeofenceSaveParam;
import cn.tedu.ivos1.geofence.pojo.entity.Geofence;
import cn.tedu.ivos1.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos1.geofence.service.GeofenceService;
import cn.tedu.ivos1.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos1.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos1.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    GeofenceMapper geofenceMapper;
    @Autowired
    VehicleMapper vehicleMapper;
    @Override
    public List<GeofenceVO> selectGeo(GeofenceQuery geofenceQuery) {
        log.debug("查询围栏业务，参数={}",geofenceQuery);
        List<GeofenceVO> list = geofenceMapper.selectGeo(geofenceQuery);
        return list;
    }

    @Override
    public void changeStatus(GeofenceSaveParam geofenceSaveParam) {
        log.debug("更新围栏状态业务，参数={}",geofenceSaveParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceSaveParam,geofence);
        geofence.setUpdateTime(new Date());
        geofenceMapper.update(geofence);
    }

    @Override
    public void saveGeofence(GeofenceSaveParam geofenceSaveParam) {
        log.debug("保存围栏业务，参数={}",geofenceSaveParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceSaveParam,geofence);
        if (geofence.getId()==null){
            geofence.setStatus("1");
            geofence.setCreateTime(new Date());
            geofenceMapper.insert(geofence);
        }else {
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }
    }

    @Override
    public void deleteGeoById(Long id) {
        log.debug("删除围栏业务，参数={}",id);
        //先要确定该围栏没有绑定车辆
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        if (list.size()>0 && list != null){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else {
            geofenceMapper.deleteGeoById(id);
        }
    }
}
